<script setup lang="ts">
import { h, reactive, ref } from 'vue';
import type { DataTableColumns } from 'naive-ui';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { deleteDataApi, fetchDataApiList, offlineApi, publishApi } from '@/service/api';
import { useBoolean } from '@sa/hooks';
import DataApiOperateDrawer from './modules/data-api-operate-drawer.vue';
import ApiTestModal from './modules/api-test-modal.vue';
import ApiLogsDrawer from './modules/api-logs-drawer.vue';
import ApiStatisticsModal from './modules/api-statistics-modal.vue';

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean();
const { bool: operateDrawerVisible, setTrue: openOperateDrawer, setFalse: closeOperateDrawer } = useBoolean();
const { bool: testModalVisible, setTrue: openTestModal, setFalse: closeTestModal } = useBoolean();
const { bool: logsDrawerVisible, setTrue: openLogsDrawer, setFalse: closeLogsDrawer } = useBoolean();
const { bool: statsModalVisible, setTrue: openStatsModal, setFalse: closeStatsModal } = useBoolean();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  path: '',
  status: ''
});

const tableData = ref<any[]>([]);
const total = ref(0);
const operateType = ref<'add' | 'edit'>('add');
const editingData = ref<any>(null);
const selectedApiId = ref<number | null>(null);

const statusOptions = [
  { label: '全部', value: '' },
  { label: '草稿', value: 'DRAFT' },
  { label: '已发布', value: 'PUBLISHED' },
  { label: '已下线', value: 'OFFLINE' }
];

const columns: DataTableColumns<any> = [
  { key: 'id', title: 'ID', width: 80, align: 'center' },
  { key: 'name', title: 'API名称', minWidth: 150, ellipsis: { tooltip: true } },
  { key: 'path', title: 'API路径', minWidth: 200, ellipsis: { tooltip: true } },
  {
    key: 'method',
    title: '请求方法',
    width: 100,
    align: 'center',
    render: row => {
      const type = row.method === 'GET' ? 'success' : 'info';
      return h(NTag, { type }, () => row.method);
    }
  },
  {
    key: 'status',
    title: '状态',
    width: 100,
    align: 'center',
    render: row => {
      const statusMap: Record<string, { type: any; label: string }> = {
        DRAFT: { type: 'default', label: '草稿' },
        PUBLISHED: { type: 'success', label: '已发布' },
        OFFLINE: { type: 'warning', label: '已下线' }
      };
      const status = statusMap[row.status] || { type: 'default', label: row.status };
      return h(NTag, { type: status.type }, () => status.label);
    }
  },
  { key: 'version', title: '版本', width: 80, align: 'center' },
  { key: 'authType', title: '鉴权类型', width: 100, align: 'center' },
  { key: 'rateLimit', title: '限流(次/秒)', width: 120, align: 'center' },
  { key: 'createTime', title: '创建时间', width: 180, ellipsis: { tooltip: true } },
  {
    key: 'actions',
    title: '操作',
    width: 320,
    align: 'center',
    fixed: 'right',
    render: row => {
      const buttons = [
        h(NButton, { size: 'small', onClick: () => handleView(row) }, () => '查看'),
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleEdit(row) }, () => '编辑'),
        h(NButton, { size: 'small', type: 'info', onClick: () => handleTest(row) }, () => '测试')
      ];

      if (row.status === 'DRAFT') {
        buttons.push(
          h(
            NPopconfirm,
            { onPositiveClick: () => handlePublish(row.id) },
            {
              default: () => '确认发布此API吗？',
              trigger: () => h(NButton, { size: 'small', type: 'success' }, () => '发布')
            }
          )
        );
      }

      if (row.status === 'PUBLISHED') {
        buttons.push(
          h(
            NPopconfirm,
            { onPositiveClick: () => handleOffline(row.id) },
            {
              default: () => '确认下线此API吗？',
              trigger: () => h(NButton, { size: 'small', type: 'warning' }, () => '下线')
            }
          )
        );
      }

      buttons.push(
        h(NButton, { size: 'small', onClick: () => handleViewLogs(row.id) }, () => '日志'),
        h(NButton, { size: 'small', onClick: () => handleViewStats(row.id) }, () => '统计'),
        h(
          NPopconfirm,
          { onPositiveClick: () => handleDelete(row.id) },
          {
            default: () => '确认删除吗？',
            trigger: () => h(NButton, { size: 'small', type: 'error' }, () => '删除')
          }
        )
      );

      return h(NSpace, { justify: 'center' }, () => buttons);
    }
  }
];

async function getTableData() {
  startLoading();
  try {
    const { data } = await fetchDataApiList(queryParams);
    if (data) {
      tableData.value = data.rows || [];
      total.value = data.total || 0;
    }
  } finally {
    endLoading();
  }
}

function handleQuery() {
  queryParams.pageNum = 1;
  getTableData();
}

function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    name: '',
    path: '',
    status: ''
  });
  getTableData();
}

function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;
  openOperateDrawer();
}

function handleView(row: any) {
  operateType.value = 'edit';
  editingData.value = { ...row };
  openOperateDrawer();
}

function handleEdit(row: any) {
  operateType.value = 'edit';
  editingData.value = { ...row };
  openOperateDrawer();
}

function handleTest(row: any) {
  selectedApiId.value = row.id;
  openTestModal();
}

function handleViewLogs(id: number) {
  selectedApiId.value = id;
  openLogsDrawer();
}

function handleViewStats(id: number) {
  selectedApiId.value = id;
  openStatsModal();
}

async function handlePublish(id: number) {
  try {
    await publishApi(id);
    window.$message?.success('发布成功');
    getTableData();
  } catch (error) {
    console.error('发布失败:', error);
  }
}

async function handleOffline(id: number) {
  try {
    await offlineApi(id);
    window.$message?.success('下线成功');
    getTableData();
  } catch (error) {
    console.error('下线失败:', error);
  }
}

async function handleDelete(id: number) {
  try {
    await deleteDataApi([id]);
    window.$message?.success('删除成功');
    getTableData();
  } catch (error) {
    console.error('删除失败:', error);
  }
}

function handleOperateSuccess() {
  closeOperateDrawer();
  getTableData();
}

function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getTableData();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getTableData();
}

// 初始化
getTableData();
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="数据服务API管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          新增API
        </NButton>
      </template>

      <div class="h-full flex-col">
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NInput v-model:value="queryParams.name" placeholder="API名称" clearable style="width: 200px" />
            <NInput v-model:value="queryParams.path" placeholder="API路径" clearable style="width: 200px" />
            <NSelect v-model:value="queryParams.status" :options="statusOptions" placeholder="状态" clearable
              style="width: 150px" />
          </NSpace>
          <NSpace>
            <NButton type="primary" @click="handleQuery">
              <icon-ic-round-search class="mr-4px text-20px" />
              查询
            </NButton>
            <NButton @click="handleReset">
              <icon-ic-round-refresh class="mr-4px text-20px" />
              重置
            </NButton>
          </NSpace>
        </NSpace>

        <NDataTable :columns="columns" :data="tableData" :loading="loading" :scroll-x="1600" :flex-height="true"
          :single-line="false" class="sm:h-0 sm:flex-1-hidden" />

        <NPagination v-model:page="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :item-count="total"
          :page-sizes="[10, 20, 30, 50]" show-size-picker class="mt-10px" @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange" />
      </div>
    </NCard>

    <DataApiOperateDrawer v-model:visible="operateDrawerVisible" :operate-type="operateType" :row-data="editingData"
      @success="handleOperateSuccess" />

    <ApiTestModal v-model:visible="testModalVisible" :api-id="selectedApiId" />

    <ApiLogsDrawer v-model:visible="logsDrawerVisible" :api-id="selectedApiId" />

    <ApiStatisticsModal v-model:visible="statsModalVisible" :api-id="selectedApiId" />
  </div>
</template>
